package algorithm;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;

public class leetcode_0056 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0]==o2[0]) return o2[1]-o1[1];
                return o1[0]-o2[0];
            }
        });
        LinkedList <int[]> list=new LinkedList<>();
        int tem=intervals[0][0];
        list.add(intervals[0]);
        int len=intervals.length;
        for(int i=1;i<len;++i){
            if(intervals[i][0]!=tem){
                list.add(intervals[i]);
                tem=intervals[i][0];
            }
        }
        int start=list.get(0)[0];
        int end=list.get(0)[1];
        int num=0;
        len=list.size();
        for(int i=1;i<len;++i){
            if(end<list.get(i)[0]){
                int [] template={start,end};
                intervals[num]=template;
                num++;
                start=list.get(i)[0];
                end=list.get(i)[1];
            }
            else {
                end=Math.max(end,list.get(i)[1]);
            }
        }
        int [] template={start,end};
        intervals[num]=template;
        num++;
        int[][] result=new int[num][2];
        for(int i=0;i<num;++i){
            result[i]=intervals[i];
        }
        return result;
    }
}
